Python Polymorphism

您所在的位置:网站首页 python polymorphism Python Polymorphism

Python Polymorphism

#Python Polymorphism | 来源: 网络整理| 查看: 265

Polymorphism in Python Object Oriented Polymorphism

The word polymorphism represents having multiple forms. In OOP, polymorphism means a same-named method can have multiple behaviors or signatures.

The same function or method can perform multiple tasks. In software development, the concept of polymorphism is very important.

Example1

Here, a multiply function is used to multiply two numbers as well as three numbers. So, it is showing multiple properties.

def multiply(a,b,c=1): print(a*b*c) multiply(1,2,1) multiply(2,3) Output 2 6 Example2

Let us create two classes having similar method names. Also, create a common interface for getting the multiple forms of the same methods.

class Cat: def sound(self): print("A cat is meowing.") class Dog: def sound(self): print("A dog is barking.") def check_polymorphism(obj): obj.sound() cat1=Cat() dog1=Dog() check_polymorphism(cat1) check_polymorphism(dog1)

Here, in both classes, there is a common method which is sound. This sound method shows polymorphism for two objects of different classes.

Output A cat is meowing. A dog is barking. Duck Typing in Python

It is the implementation of polymorphism where the type or the class of an object is less important than the method it defines.

For example, if a bird walks like a duck, quacks like a duck, swims like a duck, then any bird is a duck. So, in duck typing, the class of the object does not matter.

If the methods of two completely different classes are the same then both are taken as the same.

Example

In the example, There are two classes having similar behavior following the duck typing concept.

class PyCharm: def execute(self): print("Compiling..") print("Running...") print("In pycharm...") class OwnEditor: def execute(self): print("Spell check.") print("Convention check.") print("Compiling..") print("Running......") print("In my own editor\n\n") class Laptop: def code(self,ide): ide.execute() ide1=OwnEditor() ide2=PyCharm() lap1=Laptop() lap1.code(ide1) lap1.code(ide2) Output Spell check. Convention check. Compiling.. Running...... In my own editor Operator overloading

Basically, operators have it's own predefined meaning and task. Any operators perform their tasks based on what they are pre-defined to do.

For example, the '+' operator is used to add two integers. Also, this is used to concatenate two strings. When we type num1+num2, behind the scene, integer class calls for __add__() method.

Example >>>2+3 5 >>>2*3 6

Same thing can be done with following way.

>>>int.__add__(2,3) 5 >>>int.__mul__(2,3) 6

We are able to add and multiply two integers here because class 'int' belongs __add__() and __mul__() methods which are being called when we simply type '+' and '*'. behind the scene.

What if we try to add and multiply the object in our own classes? The simple answer is we will get an error as follows.

class StudentMark: def __init__(self, mark1, mark2): self.mark1=mark1 self.mark2=mark2 student_mark1=StudentMark(50,35) student_mark2=StudentMark(40,60) print(student_mark1+student_mark2) Output print(student_mark1+student_mark2) TypeError: unsupported operand type(s) for +: 'StudentMark' and 'StudentMark'

Here we got an error as above because our own class StudentMark doesn't have the method to call an operator. In this situation, operator overloading comes into the picture. We define operator ourselves for our own class object as follows.

class Number: def __init__(self, num): self.num=mark1 def __add__(self,other): return self.num+other.num num1=Number(100) num1=Number(200) result=num1+num1 print(result) Output 300 Method Overloading

If Class is having multiple methods with the same name, then it is called method overloading. By default, Python does not support method overloading but there are several methods to achieve it.

In python, if we try to implement method overloading, we can only use the method which is most latest.

Example def Hello(): print("Hello World>>1!") def Hello(): print("Hello World>>2!") def Hello(): print("Hello World>>3!") hello() Output Hello World>>3! #last one is printed.

To implement method overloading, we can use Multiple Dispatch Decorator聽as follows: It can be installed by the following command.

pip3 install multipledispatch Example from multipledispatch import dispatch class CalculateSum: @dispatch(int, int) def sum(num1,num2): return num1+num2 @dispatch(int,int,int) def sum(num1,num2,num3): return num1+num2+num3 @dispatch(str,str,str) def sum(str1,str2,str3): return str1+str2+str3 test1=CalculateSum() sum1=test1.sum(2,3) sum2=test1.sum(1,2,3) sum3=test1.sum("Hello ","Python ","TheRighWay!") print(sum1) print(sum2) print(sum3) Output 5 6 Hello PythonTheRightWay!

So, using dispatch decorator we are able to use method overloading in python efficiently.

Method Overriding

Method overriding is the concept in OOP in which a method of sub-class or child-class overrides the method of parent-class.

In another word, Overriding is the property of a class to change the implementation of a method provided by one of its base classes.

In inheritance, a child class can access the methods and attributes of the inherited parent class. For example, let us consider, A parent-class has a method X() which class is being inherited by class B. Now, sub-class B can access X() method. Also, if B sub-class which is inheriting parent-class A creates the same method X() with the same arguments and same signature then it is called as method X() of sub-class B is overriding the X() method of parent-class B.

Example

In inheritance, a subclass accesses its parent class's methods.

class A: def show(): print("In class A.") class B(A): pass obj=B() obj.show() Output In class A.

After implementation of method overriding, sub-class uses its own class even when sub-class is inheriting parent-class. That means a method of sub-class is overriding the method of parent-class.

class A: def show(): print("In class A.") class B(A): def show(): print("In class B.") obj=B() obj.show() Output In class B. Previous: Inheritance in Python Next: Encapsulation in Python


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3